package io.gitee.thinkbungee.crud.mybatis.mapper.method;

import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import org.apache.ibatis.executor.keygen.NoKeyGenerator;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;

/**
 * 批量新增
 *
 * @author chenyichang
 * @date 2022/2/17
 */
public class InsertBatch extends AbstractMethod {

    @Override
    public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
        //批量新增的sql
        final String sql = "<script>insert into %s %s values %s</script>";
        final String fieldSql = createFiledSql(tableInfo);
        final String valueSql = createValueSql(tableInfo);
        //生成最终的sql
        final String sqlResult = String.format(sql, tableInfo.getTableName(), fieldSql, valueSql);
        SqlSource sqlSource = languageDriver.createSqlSource(configuration, sqlResult, modelClass);
        return this.addInsertMappedStatement(mapperClass, modelClass, "insertBatch",
                sqlSource, new NoKeyGenerator(), null, null);

    }

    /**
     * 拼装 值SQL
     *
     * @param tableInfo
     * @return
     */
    private String createValueSql(TableInfo tableInfo) {
        StringBuilder sb = new StringBuilder();
        sb.append("<foreach collection=\"list\" item=\"item\" index=\"index\" open=\"(\" separator=\"),(\" close=\")\">");
        //主键
        sb.append("#{item.").append(tableInfo.getKeyProperty()).append("},");
        tableInfo.getFieldList().forEach(
                f -> sb.append("{item.").append(f.getProperty()).append("},"));
        //删除最后一个逗号
        sb.delete(sb.length() - 1, sb.length());
        sb.append("</foreach>");
        return sb.toString();

    }

    /**
     * 表中字段SQL
     *
     * @param tableInfo
     * @return
     */
    private String createFiledSql(TableInfo tableInfo) {
        StringBuilder sb = new StringBuilder();
        //主键
        sb.append(tableInfo.getKeyColumn()).append(",");
        tableInfo.getFieldList().forEach(
                f -> sb.append(f.getColumn()).append(","));
        //删除最后一个逗号
        sb.delete(sb.length() - 1, sb.length());
        //加括号
        sb.insert(0, "(");
        sb.append(")");
        return sb.toString();
    }
}
